<?php

namespace Modules;

use Admin\Models\sys\XhsysShortCut;
use Admin\Models\sys\XhsysUserShortCut;
use Admin\Models\user\XhsysUser;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Di;
use Helpers\Main;
use Helpers\Hrm;

class ShortCut
{
    public function __construct()
    {
        $this->UserId = Main::getLoginUserInfo('userId');
        if (!$this->UserId) {
            throw new \Exception('缺少用户id');
        }
    }

    private static $enums = [
        'iOpenMode' => [1 => '弹窗', 2 => '页签'],
    ];

    /**
     * 根据ID获取快捷键详情（管理员）
     *
     * @param $id --快捷键ID
     * @return mixed
     * @throws \Exception
     *
     * create by ylf 20181101
     */
    public function shortDetails($id)
    {
        $userData = XhsysShortCut::findFirst([
            'conditions' => 'bDelete = 0 AND iId = :id: ',
            'bind' => ['id' => $id]
        ]);
        if ($userData) {
            $userData = $userData->toArray();
            return $userData;
        } else {
            throw new \Exception('数据不存在');
        }
    }

    /**
     * 分配快捷键权限（管理员）
     *
     * @param $logo --快捷键logo
     * @param $name --快捷键命名称
     * @param $url --快捷键url
     * @param $model --模块
     * @param $openMode --打开方式 1 弹窗 2 页签
     * @param array $tag --权限标签
     * @param bool $public --是否公用，true:公用,直接存在个人配置表  默认非公用
     * @throws \Exception
     *
     * create by ylf 20181101
     */
    public function insertShortCut($logo, $name, $url, $model, $openMode = 1, $tag, $public = false)
    {
        if (!$logo) {
            throw new \Exception('logo不能为空');
        }
        if (!$name) {
            throw new \Exception('名称不能为空');
        }
        if (!$url) {
            throw new \Exception('url地址不能为空');
        }
        if (!$tag) {
            throw new \Exception('权限标签不能为空');
        }
        if (!$model) {
            throw new \Exception('模块不能为空');
        }
        if ($public) {
            //默认快捷键
            $data = array(
                'sLogo' => $logo,
                'sName' => $name,
                'vUrl' => $url,
                'sModel' => $model,
                'iOpenMode' => $openMode,
                'sTag' => $tag,
                'tCreateDate' => date('Y-m-d,H:i:s', time()),
            );
            $this->addData($data, 'ShortCut');
            $userData = XhsysShortCut::findFirst([
                'conditions' => 'bDelete = 0 AND sTag = :tag: ',
                'bind' => ['tag' => $tag]
            ])->toArray();
            $data['iMid'] = $userData['iId'];
            $data['iUserId'] = 0;
            $this->addData($data, 'publicShortCut');

        } else {
            $dataInfo = array(
                'sLogo' => $logo,
                'sName' => $name,
                'sModel' => $model,
                'vUrl' => $url,
                'iDefault' => 2,
                'sTag' => $tag,
                'iOpenMode' => $openMode,
                'tCreateDate' => date('Y-m-d,H:i:s', time()),
            );
            $this->addData($dataInfo, 'ShortCut');
        }
    }


    /**
     * 管理员删除某项快捷键(所分配的权限用户都将失效)
     *
     * @param $id --管理员快捷键配置表ID
     * @return bool
     * @throws \Exception
     *
     * create by ylf 20181102
     */
    public function delShortCut($id)
    {
        //单删
        if (!$id) {
            throw new \Exception('快捷键ID不能为空');
        }
        if (is_array($id)) {
            throw new \Exception('不能传数组格式');
        }
        $this->delPublic($id);
        return true;
    }


    /**
     * 管理员批量删除某项快捷键(所分配的权限用户都将失效)
     *
     * @param array $idArr --管理员快捷键配置表ID
     * @return bool
     * @throws \Exception
     *
     * create by ylf 20181102
     */
    public function delShortCuts($idArr = [])
    {
        //批量删
        $idArr = array_filter($idArr);
        $idArr = array_unique($idArr);

        if (count($idArr) > 0) {
            foreach ($idArr as $vaArr) {
                $this->delPublic($vaArr);
            }
        }
        return true;
    }

    /**
     * 管理员快捷键列表
     *
     * @param string $key --关键字
     * @param string $type --默认  0全部 1默认 2非默认
     * @param string $model --模块
     * @return array|string
     * @throws \Exception
     *
     * create by ylf 20181106
     */
    public function shortlist($key = '', $type, $model)
    {
        if (!$this->UserId) {
            throw new \Exception('缺少用户id');
        }
        $user = Di::getDefault()->get('modelsManager')->createBuilder()
            ->columns("u.*")
            ->from(['u' => 'Admin\Models\sys\XhsysShortCut'])
            ->where('u.bDelete = 0 ')
            ->orderBy('u.tCreateDate desc');

        switch ($type) {
            case '1':

                $user->andWhere('u.iDefault=1');
                break;
            case '2':
                $user->andWhere('u.iDefault=2');
                break;
            default :
                break;
        }

        if ($key) {
            $user->andWhere('u.sName like :key:', array('key' => '%' . $key . '%'));
        }
        if ($model) {
            $user->andWhere('u.sModel like :model:', array('model' => '%' . $model . '%'));
        }
        $data = Main::runBuilderPaginator($user, true);
        foreach ($data['rows'] as $index => $row) {
            $data['rows'][$index]['iOpenMode'] = self::$enums['iOpenMode'][$row['iOpenMode']];
        }
        return $data;
    }


    /**
     *  管理员删除快捷键公共删除方法（不可调用）
     *
     * @param $id
     * @throws \Exception
     *
     * create by   ylf 20181102
     */
    public function delPublic($id)
    {
        $obj = XhsysShortCut::findFirst([
            'conditions' => 'bDelete = 0  AND sTag= :tag:',
            'bind' => ['tag' => $id]
        ]);
        if ($obj) {
            $obj->bDelete = 1;
            if (!$obj->save()) {

                throw new \Exception('操作失败');
            } else {
                $userData = XhsysUserShortCut::findFirst([
                    'conditions' => 'bDelete = 0 AND sTag = :mid: ',
                    'bind' => ['mid' => $id]
                ]);
                if ($userData) {
                    $userData->delete();
                }
            }
        } else {
            $uData = XhsysUserShortCut::findFirst([
                'conditions' => 'bDelete = 0  AND sTag= :tag:',
                'bind' => ['tag' => $id]
            ]);
            if ($uData) {
                $uData->bDelete = 1;
                if (!$uData->save()) {
                    throw new \Exception('操作失败');
                } else {
                    $uData = $uData->toArray();
                    $userDatas = XhsysUserShortCut::find([
                        'conditions' => 'bDelete = 0 AND sTag = :tag: ',
                        'bind' => ['tag' => $uData['sTag']]
                    ]);
                    if ($userDatas) {
                        $userDatas->delete();
                    }
                }
            }
        }

    }

    /**
     * 个人快捷键列表(含公用部分)
     *
     * @return mixed
     * @throws \Exception
     *
     * create by ylf 20181102
     */
    public function allUserShortCut()
    {
        $mainFlow = XhsysUserShortCut::find([
            'conditions' => 'bDelete = 0  AND  iUserId = :userId: ',
            'bind' => ['userId' => $this->UserId]
        ])->toArray();

        if (!$mainFlow) {
            //未设置过显示公用部分
            $mainFlow = XhsysUserShortCut::find([
                'conditions' => 'bDelete = 0  AND  iUserId = 0',
            ])->toArray();
        }
        foreach ($mainFlow as $key => $value) {
            $a = Power::exist($value['sTag'], $this->UserId);
            if ($a) {
                //有权限的情况下判断是否选中
                $selected = $this->bSelect($value['sTag']);
                file_put_contents('log.txt', $selected, FILE_APPEND);
                if ($selected) {
                    $mainFlow[$key]['selected'] = '1';
                } else {
                    $mainFlow[$key]['selected'] = '0';
                }

            } else {
                $mainFlow[$key] = "";
            }
        }
        $dataList = array_filter($mainFlow);
        return $dataList;

    }

    /**
     * 个人设置快捷键列表
     *
     * @return array
     *
     * create by ylf 20181115
     */
    public function userShortCuts()
    {

        $sql = "SELECT iId,sModel,sTag FROM `XHSys_ShortCut` where bDelete='0'  GROUP BY sModel";
        $data = Di::getDefault()->get('db')->fetchAll($sql);

        foreach ($data as $k => $v) {
            $mainFlowss = XhsysShortCut::find([
                'conditions' => 'bDelete = 0 AND sModel=:model: ',
                'bind' => ['model' => $v['sModel']]
            ])->toArray();

            $a = Power::exist($v['sTag'], $this->UserId);
            if ($a) {
                //有权限的情况下判断是否选中
                foreach ($mainFlowss as $key => $val) {
                    $selected = $this->bSelect($val['sTag']);
                    if ($selected) {
                        $mainFlowss[$key]['selected'] = '1';
                    } else {
                        $mainFlowss[$key]['selected'] = '0';
                    }
                    $mainFlowss[$key]['public'] = $val['iDefault'];
                }

                $datas[$k]['model'] = $v['sModel'];
                $datas[$k]['rows'] = $mainFlowss;
            } else {
                $datas[$k] = "";
            }

        }
        return $datas;
    }

    /**
     * 判断数据是否存在个人配置中
     *
     * @param $tag
     * @return bool
     *
     * create by ylf  20181114
     */
    public function bSelect($tag)
    {

        $mainFlow = XhsysUserShortCut::findFirst([
            'conditions' => 'bDelete = 0 AND  iUserId = :userId:',
            'bind' => ['userId' => $this->UserId]
        ]);
        if ($mainFlow) {
            $mainFlows = XhsysUserShortCut::findFirst([
                'conditions' => 'bDelete = 0 AND  iUserId = :userId: AND sTag=:tag:',
                'bind' => ['userId' => $this->UserId, 'tag' => $tag]
            ]);
            if ($mainFlows) {
                return true;
            } else {
                return false;
            }
        } else {
            $mainFlowss = XhsysUserShortCut::findFirst([
                'conditions' => 'bDelete = 0 AND  iUserId = 0 AND sTag=:tag:',
                'bind' => ['tag' => $tag]
            ]);

            if ($mainFlowss) {
                return true;
            } else {
                return false;
            }
        }

    }

    /**
     *  个人加入快捷键
     *
     * @param array $id --XhsysUserShortCut得默认快捷键iID或XhsysShortCut的tag
     * @param array $public --是否默认
     * @return bool
     * @throws \Exception
     *
     * create by 20181102
     */
    public function addUserShortCut($id = [], $public = [])
    {
        foreach ($public as $value) {
            foreach ($id as $valid) {
                if ($value == '1') {
                    $data = XhsysUserShortCut::findFirst([
                        'conditions' => 'bDelete = 0  AND sTag= :tag:',
                        'bind' => ['tag' => $valid]
                    ]);

                    if ($data) {
                        $data = $data->toArray();
                        $dataInfo = array(
                            'sLogo' => $data['sLogo'],
                            'sName' => $data['sName'],
                            'vUrl' => $data['vUrl'],
                            'iMid' => $data['iId'],
                            'sTag' => $data['sTag'],
                            'sModel' => $data['sModel'],
                            'iOpenMode' => $data['iOpenMode'],
                            'tCreateDate' => date('Y-m-d,H:i:s', time()),
                        );
                        $this->addData($dataInfo, 'userShortCut');

                    }
                 }
                 else {
                    $data = XhsysShortCut::findFirst([
                        'conditions' => 'bDelete = 0  AND sTag= :tag:',
                        'bind' => ['tag' => $valid]
                    ]);

                    if ($data) {
                        $data = $data->toArray();
                        $dataInfo = array(
                            'sLogo' => $data['sLogo'],
                            'sName' => $data['sName'],
                            'vUrl' => $data['vUrl'],
                            'iMid' => $data['iId'],
                            'sTag' => $data['sTag'],
                            'sModel' => $data['sModel'],
                            'iOpenMode' => $data['iOpenMode'],
                        );
                        $this->addData($dataInfo, 'userShortCut');
                    }
                }
            }
        }
    }

    /**
     *  个人移除快捷键
     *
     * @param array $id --XhsysUserShortCut得默认快捷键iID或XhsysShortCut的iID
     * @param array $public --是否默认
     * @return bool
     * @throws \Exception
     *
     * create by 20181102
     */
    public function delUserShort($id = [], $public = [])
    {
        foreach ($id as $valid) {
            $userTest = XhsysUserShortCut::findFirst([
                'conditions' => 'bDelete = 0  AND sTag= :tag: AND iUserId=:userId:',
                'bind' => ['tag' => $valid, 'userId' => $this->UserId]
            ]);

            if ($userTest) {
                $userTest->delete();
            }
        }

        return true;

    }


    /**
     * 添加数据（不可调用）
     *
     * @param $dataInfo
     * @param $table
     * @throws \Exception
     *
     * create by ylf 20181101
     */

    public function addData($dataInfo, $table)
    {

        if ($table == "ShortCut") {
            $obj = new XhsysShortCut();
            //根据权限标签查询数据是否存在
            $dataInfo['iCreateUserId'] = $this->UserId;
            $mainFlow = XhsysShortCut::findFirst([
                'conditions' => 'bDelete = 0  AND sTag= :tag:',
                'bind' => ['tag' => $dataInfo['sTag']]
            ]);

            if ($mainFlow) {
                //如果数据存在执行更新
                if (!$mainFlow->Update($dataInfo)) {
                    throw new \Exception('数据更新失败');
                } else {
                    //同步个人配置信息修改
                    $this->updateData($dataInfo);
                }
            } else {
                if (!$obj->save($dataInfo)) {
                    throw new \Exception('数据操作失败');
                }
            }

        }
        if ($table == "publicShortCut") {
            //管理员默认
            $obj = new XhsysUserShortCut();
            $dataInfo['tCreateDate'] = date('Y-m-d,H:i:s', time());
            $dataInfo['iCreateUserId'] = $this->UserId;
            $mainFlow = XhsysUserShortCut::findFirst([
                'conditions' => 'bDelete = 0  AND sTag= :tag:',
                'bind' => ['tag' => $dataInfo['sTag']]
            ]);

            if ($mainFlow) {
                //如果数据存在执行更新
                if (!$mainFlow->Update($dataInfo)) {
                    throw new \Exception('数据更新失败');
                } else {
                    //同步个人配置信息修改
                    $this->updateData($dataInfo);
                }
            } else {

                if (!$obj->save($dataInfo)) {
                    throw new \Exception('数据操作失败');
                }
            }

        }


        if ($table == "userShortCut") {
            //个人操作加入快捷键
            $obj = new XhsysUserShortCut();
            $dataInfo['tCreateDate'] = date('Y-m-d,H:i:s', time());
            $dataInfo['iCreateUserId'] = $this->UserId;
            $dataInfo['iUserId'] = $this->UserId;
            $mainFlow = XhsysUserShortCut::findFirst([
                'conditions' => 'bDelete = 0  AND sTag= :tag: AND iUserId > 0',
                'bind' => ['tag' => $dataInfo['sTag']]
            ]);

            if ($mainFlow) {
                if (!$mainFlow->Update($dataInfo)) {
                    throw new \Exception('数据更新失败');
                };
            } else {
                if (!$obj->save($dataInfo)) {
                    throw new \Exception('数据操作失败');
                }

            }
        }
    }


    /**
     *select 获取模块
     *
     * @return array
     *
     * create by ylf 20181120
     */
    public function modelArr()
    {

        $sql = "SELECT iId,sModel,sTag FROM `XHSys_ShortCut` where bDelete='0'  GROUP BY sModel";
        $data = Di::getDefault()->get('db')->fetchAll($sql);
        $schoolList = array_column($data, 'sModel', 'iId');
        return $schoolList;
    }

    /**
     * 检测权限标签
     *
     * @param $tag --权限标签
     * @return bool
     *
     * create by ylf 20181122
     */
    public function checkTag($tag)
    {
        $data = XhsysShortCut::findFirst([
            'conditions' => 'bDelete = 0  AND sTag= :tag: ',
            'bind' => ['tag' => $tag]
        ]);
        if ($data) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据权限标签判断是否默认
     *
     * @param $tag --权限标签
     * @param $id --ID
     * @return bool
     *
     * create by ylf 20181122
     */
    public function publicTag($tag, $id)
    {
        $mainFlow = XhsysUserShortCut::findFirst([
            'conditions' => 'bDelete = 0  AND sTag= :tag:  AND iId= :id: ',
            'bind' => ['tag' => $tag, 'id' => $id]
        ]);
        if ($mainFlow) {
            //默认
            return true;
        } else {
            return false;
        }
    }

    /**
     * 同步更新
     *
     * @param $dataInfo
     * @throws \Exception
     *
     * create by ylf 20181122
     */
    public function updateData($data)
    {
        $mainFlow = XhsysUserShortCut::find([
            'conditions' => 'bDelete = 0  AND sTag= :tag: AND iUserId>0 ',
            'bind' => ['tag' => $data['sTag']],
        ]);
        if ($mainFlow) {
            $dataInfo = array(
                'sLogo' => $data['sLogo'],
                'sName' => $data['sName'],
                'vUrl' => $data['vUrl'],
                'sTag' => $data['sTag'],
                'sModel' => $data['sModel'],
                'iOpenMode' => $data['iOpenMode'],
            );
            if (!$mainFlow->Update($dataInfo)) {
                throw new \Exception('数据更新失败');
            }
           return true;
        }

    }


}